package com.kzw.oa.comm.web;

import java.net.URL;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.kzw.core.util.web.ServletUtils;

@Controller
public class FileDownloadAction {

	/**
	 * 通用文件下载：path是一个url路径
	 * */
	@RequestMapping("/file/download")
	public void download(String path, String title, HttpServletRequest req, HttpServletResponse resp) {
		String ext = FilenameUtils.getExtension(path);
		if(StringUtils.isBlank(title)) {
			title = FilenameUtils.getName(path);
		}
		if(!title.endsWith("."+ext)) {
			title += "." + ext;
		}
		
		ServletUtils.setFileDownloadHeader(resp, title);
		
		// path ==> url
		if(!StringUtils.startsWithAny(path, "http://", "https://")) {
			path = "http://127.0.0.1:" + req.getServerPort() + path;
		}
		
		try {
			IOUtils.copy(new URL(path).openStream(), resp.getOutputStream());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
